import router from "@/router";
import { menu, myMenu, nurseMenu } from "@/utils/menu";
import store from "@/store";
let whiteList = ["/login", "/authentication"];
import NProgress from "nprogress";
import "nprogress/nprogress.css";
router.beforeEach((to, from, next) => {
  document.title = "运动健康专家端";
  NProgress.start();
  if (whiteList.includes(to.path)) {
    NProgress.done();
    next();
  } else {
    if (store.state.token) {
      let userType = store.state.login_info.userType;
      let rule = to.meta.rule.includes(userType);
      console.log(rule);
      if (!rule) {
        next("/404");
        NProgress.done();
      } else {
        setActiveTab(menu, myMenu, to.path);
        next();
        NProgress.done();
      }
    } else {
      NProgress.done();
      next("/");
    }
  }
});

//生成菜单   SETMENU设置菜单   SETACTIVEPATH设置当前路由
const setActiveTab = (arr1, arr2, path) => {
  if (store.state.login_info.userType == "3") {
    //专家身份
    if (store.state.menu_arr.length == 0) {
      store.commit("SETMENU", check(path));
    } else {
      let whichArr = check(path);
      //当前路由所在菜单不是 vuex里面的菜单  这切换菜单
      if (whichArr && whichArr != store.state.menu_arr) {
        store.commit("SETMENU", whichArr);
      }
    }
  } else if (store.state.login_info.userType == "4") {
    //护士身份
    store.commit("SETMENU", nurseMenu);
    store.commit("SETACTIVEPATH", path);
  }
};

//判断当前路由在哪个菜单
const check = (path) => {
  for (let i = 0; i < menu.length; i++) {
    if (menu[i].href == path) {
      store.commit("SETACTIVEPATH", path);
      return menu;
    }
  }
  for (let i = 0; i < myMenu.length; i++) {
    if (myMenu[i].href == path) {
      store.commit("SETACTIVEPATH", path);
      return myMenu;
    }
  }
  return false;
};
